import logging.config 
import os 
import re
import subprocess 
import sys 

from db import DbService 
from checker.file_gen_status_checker import FileGenStatusChecker

class Main(object):
    def __init__(self,argv_array):
        self.logger=logging.getlogger("Main")
        self.argv_array=argv_array

    def _parse_properties(self,properties_file):
        prop_map={}
        with open(properties_file,'r') as config_file:
            for line in config_file.readlines():
                line=line.rstrip("\r").rstrip("\n")
                match_result=re.match(r"^([^#][\w_-]+)=(.*?)$",line)
                if match_result:
                    prop_map[match_result.group(1)] = match_result.group(2)
                else:
                    self.logger.info("Skip config line {}".format(line))
        return prop_map
    
    def load_db_connection_map(self,db_config):
        return self._parse_properties(db_config)
    
    def load_cfg_map(self,properties_file):
        return self._parse_properties(properties_file)
    
    def decode_secret(self,application_properties,encode_passwd):
        if encode_passwd:
            home_location=application_properties["gmrmbatch_entegor_root_path"]
            des_key_name=application_properties["des_key_file_name"]
            des_tool_binary_name=application_properties["des_tool_binary"]
            
            des_wk_dir=os.path.join(home_location,"java","encrypt")
            des_key_file=os.path.join(des_wk_dir,des_key_name)
            des_tool_binary_file=os.path.join(des_wk_dir,des_tool_binary_name)

            if os.path.exists(des_key_file) and os.path.exists(des_tool_binary_file):
                cmd = 'cd {} && {} {} {} 1'.format(des_wk_dir,des_tool_binary_file,encode_passwd,des_key_file)
                self.logger.info("executing {}".format(cmd))
                return subprocess.getoutput(cmd)
            else:
                return None 
        else:
            self.logger.error("Cannot decode empty")
            return None 
    
    def handle_command(self):
        """
        执行命令
        :return:
        """
        app_prop_map=self.load_cfg_map(os.path.josin(env_path,"application.properties"))
        datasource_gauss_driver=app_prop_map["datasource_gauss_driver"]
        datasource_gauss_url=app_prop_map["datasource_gauss_url"]
        datasource_gauss_username=app_prop_map["datasource_gauss_username"]
        datasource_gauss_password=app_prop_map["datasource_gauss_password"]
        datasource_gauss_jar_path=app_prop_map["datasource_gauss_jar_path"]

        conn_str=[datasource_gauss_driver,datasource_gauss_url,datasource_gauss_username,datasource_gauss_password,datasource_gauss_jar_path]
        db_service=DbService(conn_str)
        if self.argv_array[1].upper()=="BATCH_CHECK":
            self.check_batch(db_service)
        elif self.argv_array[1].upper()=="FILE_CHECK":
            self.check_file(db_service)
        elif self.argv_array[1].upper()=="LIMIT_FIX":
            self.fix_limit_batch(db_service)
        elif self.argv_array[1].upper()=="LIMIT_EMPTY_FILE_GEN":
            self.fix_limit_batch_by_gen_empty_file(db_service)
        elif self.argv_array[1].upper()=="FILE_GEN_CHECK":
            self.check_file_gen(db_service)
        else:
            self.logger.info("Invalid input {}".format(self.argv_array))

    def fix_limit_batch(self,db_service):
        """
        修复限额批量
        :param db_service:
        :return:
        """
        if len(self.argv_array)==4 and re.match(r'\d{8}',self.argv_array[2]) and re.match(r'\d',self.argv_array[3]):
            batch_fixer=DailyLimitBatchFixer(db_service)
            batch_fixer.fix(self.argv_array[2],self.argv_array[3])
        else:
            logger.info("Check your input for task LIMIT_FIX: {}".format(argv_array[1:]))

    def check_file_gen(self,db_service):
        """
        文件生成状态检查
        :param db_service:
        :return:
        """
        file_gen_checker=FileGenStatusChecker(db_service)
        if len(self.argv_array)==2:
            file_gen_checker.check_gen_status()
        else:
            self.logger.info("Check your input for FILE_GEN_CHECK:{}".format(self.argv_array[1:]))



if __name__ == "__main__":
    logger_config_file_name="python_logger.conf"
    if not os.path.exists("logs"):
        os.mkdir("logs")
    env_path=os.getenv('ENV_DIR_ETC',os.getcwd())
    if os.path.exists(os.path.join(env_path,logger_config_file_name)):
        print("Use logger config in cfg dir")
        logger.config.fileConfig(os.path.join(env_path,logger_config_file_name))
    else:
        print("Use logger config in module dir")
        logging.config.fileConfig(os.path.join(os.path.dirname(sys.argv[0]).logger_config_file_name))

    # create logger
    logger_name="Main"
    logger=logging.getLogger(logger_name)

    argv_array=sys.argv 
    if argv_array[0].startswitch("python"):
        argv_array=argv_array[1:]
    if len(argv_array)==1:
        show_help()
    else:
        main=Main(argv_array)
        main.handle_command()